// ActionScript file
import com.nstar.base.event.RequestEvent;
import com.nstar.base.util.EffectUtils;
import com.nstar.base.util.GraphicsUtils;
import com.nstar.base.util.LoadXMLDelegate;
import com.nstar.base.util.Logger;
import com.nstar.pim.components.BackgroundMaker;
import com.nstar.pim.components.CustomShape;
import com.nstar.pim.components.DesignCanvas;
import com.nstar.pim.components.LoadProgressBar;
import com.nstar.pim.components.SimpleImage;
import com.nstar.pim.itemrenderer.GradientSchemeRenderer;
import com.nstar.pim.itemrenderer.LayerRenderer;
import com.nstar.pim.itemrenderer.PatternRenderer;
import com.nstar.pim.itemrenderer.SolidSchemeRenderer;
import com.nstar.pim.model.TemplatesResponder;
import com.nstar.pim.mxml.Advice;
import com.nstar.pim.mxml.CustomShapeProperties;
import com.nstar.pim.mxml.FontProperties;
import com.nstar.pim.mxml.SimpleImageProperties;
import com.nstar.pim.mxml.Toast;
import com.nstar.pim.vo.IconTypeVO;
import com.nstar.pim.vo.IconVO;
import com.nstar.taobao.TaoBaoUtils;

import flash.display.DisplayObject;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.ProgressEvent;
import flash.filters.GlowFilter;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.navigateToURL;
import flash.text.Font;
import flash.utils.ByteArray;

import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.containers.Canvas;
import mx.controls.Alert;
import mx.controls.Image;
import mx.controls.Menu;
import mx.controls.Text;
import mx.core.Application;
import mx.core.UIComponent;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.events.FlexMouseEvent;
import mx.events.ItemClickEvent;
import mx.events.ListEvent;
import mx.events.MenuEvent;
import mx.events.NumericStepperEvent;
import mx.graphics.ImageSnapshot;
import mx.graphics.codec.JPEGEncoder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.mxml.HTTPService;
import com.roguedevelopment.objecthandles.SelectionEvent;
import com.roguedevelopment.objecthandles.ObjectChangedEvent;
import mx.utils.Base64Decoder;
//import com.roguedevelopment.objecthandles.SelectionEvent;
//import com.roguedevelopment.objecthandles.ObjectChangedEvent;

var se:SelectionEvent;
var oce:ObjectChangedEvent;

public static const ASSETS_URL:String = "assets/assets.xml"; 
public static const TEMPLATES_URL:String = "assets/templates.xml";

public static const FEEDBACK_URL:String = "feedback.php";

public static const CHANGE_WIDTH:String = "changeWidth";

private var loader:LoadXMLDelegate ;

private var saved:Boolean = false;

private var logger:Logger = Logger.getInstance();

private const encoder:JPEGEncoder = new JPEGEncoder(85);
//private const encoder:PNGEncoder = new PNGEncoder();

private var file:FileReference;
private var uploadURL:URLRequest;

private static const CREATE_IMAGE:String = "http://picmaster.sinaapp.com/create_image.php";
private static const UPLOAD_IMAGE_SPACE:String = "http://picmaster.sinaapp.com/upload_image.php";
private static const UPLOAD_IMAGE_SPACE_SDK:String = "http://picmaster.sinaapp.com/upload_image_sdk.php";
private static const DOWNLOAD_IMAGE:String = "http://picmaster.sinaapp.com/download_taobao_image.php";
private static const DOWNLOAD_IMAGE_LOCAL:String = "http://picmaster.sinaapp.com/download_image_local.php";
private static const BANGPAI:String = "http://bangpai.taobao.com/group/14585210.htm";
private static const TUTORIALS:String = "http://bangpai.taobao.com/group/thread/14585210-265468829.htm";
private static const EXIT_URL:String = "https://oauth.taobao.com/logoff?client_id=12306094&redirect_uri=http://picmaster.sinaapp.com/";


[Bindable]
public var nick:String = "访客";
[Bindable]
public var userId:String;
[Bindable]
public var avatar:String;

public var sid:String;//店铺ID
public var shopTitle:String;//店铺标题
public var shopDesc:String;//店铺描述
public var shopPicPath:String;//店标地址
public var shopUrl:String;

private var app:ProductImageMaster;

private static const APP_KEY:String = TaoBaoUtils.APP_KEY_PIM;
private static const APP_SECRET:String = TaoBaoUtils.APP_SECRET_PIM;

public var taoBaoUtils:TaoBaoUtils ;

private function init():void{
	app = Application.application as ProductImageMaster; 
	
	
	//加载图标配置
	loader = new LoadXMLDelegate(this,ASSETS_URL,"object");
	loader.load();
	//画布属性
	canvas.shapeWidth = tbWidths.dataProvider[tbWidths.selectedIndex].data;
	canvas.shapeHeight = txtHeight.value;
	canvas.addEventListener(DesignCanvas.ADD_SHAPE,addShapeHandler);
	canvas.addEventListener(DesignCanvas.GETTING_COLOR,getColorCompleteHandler);
	canvas.addEventListener(DesignCanvas.END_GET_COLOR,getColorCompleteHandler);
	canvas.addEventListener(DesignCanvas.PREVIEW_COMPLETE,previewCompleteHandler);
	canvas.addEventListener(DesignCanvas.ADD_LAYER_CHILD,layerHandler);
	canvas.addEventListener(DesignCanvas.REMOVE_LAYER_CHILD,layerHandler);
	canvas.addEventListener(SelectionEvent.ADDED_TO_SELECTION,handleClickedHandler);
	canvas.addEventListener(ObjectChangedEvent.OBJECT_MOVING,objectHandler);
	canvas.addEventListener(DesignCanvas.POS,posHandler);
	
	canvas.addEventListener(DesignCanvas.CHANGE_INDEX,changeIndexHandler);
	canvas.addEventListener(DesignCanvas.DELETE_ITEM,deleteItemHandler);
	
	layers.addEventListener(LayerRenderer.CHANGE_VISIBLE,changeVisibleHandler);
	layers.addEventListener(ListEvent.ITEM_CLICK,selectLayerHandler);
	
	//创建图片服务
	uploadService.url = CREATE_IMAGE;
	upload2space.url = UPLOAD_IMAGE_SPACE_SDK;
	//下载图片到本地
	downloadImageLocalService.url = DOWNLOAD_IMAGE_LOCAL;
	
	feedbackService.url = FEEDBACK_URL;
	//
	//文件上传设置
	file = new FileReference();
	file.addEventListener(Event.SELECT,uploadHandler);
	file.addEventListener(Event.COMPLETE,uploadHandler);
	file.addEventListener(IOErrorEvent.IO_ERROR,uploadHandler);
	file.addEventListener(ProgressEvent.PROGRESS,uploadHandler);
	file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadHandler);
	//文件上传后台
	uploadURL = new URLRequest();
	uploadURL.url = UPLOAD_IMAGE_SPACE;
	
	//字体属性修改
	fontProperties.addEventListener(FontProperties.CHANGE_FONT_TEXT,changeFontHandler);
	fontProperties.addEventListener(FontProperties.CHANGE_FONT_NAME,changeFontHandler);
	fontProperties.addEventListener(FontProperties.CHANGE_FONT_SIZE,changeFontHandler);
	fontProperties.addEventListener(FontProperties.CHANGE_FONT_COLOR,changeFontHandler);
	//形状属性修改
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_BORDER_THICKNESS,changeShapePropHandler);
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_BORDER_COLOR,changeShapePropHandler);
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_FILL_TYPE,changeShapePropHandler);
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_COLOR,changeShapePropHandler);
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_ANGLE,changeShapePropHandler);
	customShapeProperties.addEventListener(CustomShapeProperties.CHANGE_ALPHA,changeShapePropHandler);
	
	simpleShapeProperties.addEventListener(CustomShapeProperties.CHANGE_ALPHA,changeSimpleImagePropHandler);
	
	txtShop.addEventListener(MouseEvent.CLICK,gotoShop);

	
	Alert.yesLabel = "是";
	Alert.noLabel = "否";
	
	GraphicsUtils.drawBackground(imgTmp,title);
}

private function gotoShop(evnt:MouseEvent):void{
	navigateToURL(new URLRequest(this.shopUrl),"_blank");
}

//显示当前选中的对象属性
private function handleClickedHandler(event:Event):void{
	var selecteditem:Object = canvas.getSelection()[0];
	//定位图层中的项
	for each(var item:Object in layers.dataProvider){
		if(item.selectedItem.name == selecteditem.name){
			layers.selectedItem = item;
			break;
		}
	}
	
	txtX.text = selecteditem.x;
	txtY.text = selecteditem.y;
	
	if(selecteditem.hasOwnProperty("filters") && selecteditem.filters!=null){
		var filters:Array = selecteditem.filters;
		if(filters[0] is GlowFilter){
			chkGlow.selected = true;
			var gf:GlowFilter = filters[0];
			var c:uint = gf.color;
			var blur:Number = gf.blurX;
			cpGlowColor.selectedColor = c;
			txtGlowSize.text = blur.toString();
		}else{
			chkGlow.selected = false;
		}
		
	}
	
	//显示对应的属性信息
	if(selecteditem is Text){
		vsProps.selectedIndex = 0;
		fontProperties.updateProperties(selecteditem as Text);
	}else if(selecteditem is CustomShape){
		vsProps.selectedIndex = 1;
		customShapeProperties.updateProperties(selecteditem as CustomShape);
	}else if((selecteditem is SimpleImage) || (selecteditem is Image)){
		vsProps.selectedIndex = 2;
		simpleShapeProperties.updateProperties(selecteditem as DisplayObject);
	}
}

private function objectHandler(event:RequestEvent):void{
	var selecteditem:Object = canvas.getSelection()[0];
	txtX.text = selecteditem.x;
	txtY.text = selecteditem.y;		
}

private function posHandler(event:RequestEvent):void{
//	txtX.text = event.request.x;
//	txtY.text = event.request.y;
}


//使用淘宝帐号登录
private function loginHandler():void{
	
}

//获取字体名称列表
private function getFonts():Array{
	var allFonts:Array = Font.enumerateFonts(true);	
	allFonts.sortOn("fontName", Array.CASEINSENSITIVE|Array.DESCENDING);
	return allFonts;
}

//获取图片字节数组
private function getImageByteArray():ByteArray{
	var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(canvas.getCanvas(), 0, encoder); 
	return imageSnap.data;
}


//获取图片,64位字符串编码
private function getImageBase64():String{
	var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(canvas.getCanvas(), 0, encoder); 
	return ImageSnapshot.encodeImageAsBase64(imageSnap);
}

private function menuHandler1(event:ItemClickEvent):void{
	switch(event.index){
		case 0:
			if(saved==false && canvas.getCanvas().numChildren>0){
				var t1:Toast = Toast.show("新建确认","亲，图片还未上传到图片空间，真的要重新设计了么？");
				t1.addEventListener(CloseEvent.CLOSE,closeHandler);
			}else{
				canvas.reset();
			}
			break;
		case 1://上传到图片空间
			var t2:Toast =Toast.show("上传确认","亲，要上传当前设计的图片到淘宝图片空间吗？");
			t2.addEventListener(CloseEvent.CLOSE,uploadConfirmHandler);
			break;
		case 2://预览
			canvas.clearSelection();
			showPreview(false);
			break;
		case 3:
			downloadImageLocal();
			break;
	}
	
}

//获取图片，并发送请求
private function getBase64Image(service:HTTPService):void{
	canvas.clearSelection();//清除选择状态
	LoadProgressBar.show();
	var request:Object = new Object();
	request.image = getImageBase64();
	request.appkey = app.top_appkey;
	request.secret = app.app_secret;
	request.sessionKey = app.top_session;
	request.userId = this.userId;
	request.nick = this.nick;
	request.width = canvas.canvas.width;
	request.height = canvas.canvas.height;
	request.sid = this.sid;
	request.shopTitle = this.shopTitle;
	request.shopDesc = this.shopDesc;
	request.shopPicPath = this.shopPicPath;
	service.send(request);
}

//上传确认
private function uploadConfirmHandler(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		getBase64Image(uploadService);
	}
}

//下载图片
private function downloadImageLocal():void{
	getBase64Image(downloadImageLocalService);
}

var oldBgType:int ;
private function showPreview(visible:Boolean):void{
	title.visible = toolbar.visible = library.visible = visible; 
	canvas.hrule.visible = canvas.vrule.visible = visible;
	canvas.previewing = !visible;
	canvas.showHVLine(visible);
	if(visible==false)
		oldBgType = canvas.canvasBgType;
	canvas.changeCanvasColor(visible?oldBgType:2);
	this.setStyle("backgroundColor",0x333333);
}

private function previewCompleteHandler(event:Event):void{
	showPreview(true);
	this.clearStyle("backgroundColor");
}

private function validateHandler():Boolean{

	return true;
}

private function closeHandler(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		canvas.reset();
		layers.dataProvider = new Array();
	}
}


private function sendByteArray(myByteArray:ByteArray):void {
    var request:URLRequest = new URLRequest(UPLOAD_IMAGE_SPACE);
    var loader: URLLoader = new URLLoader();
	loader.addEventListener(IOErrorEvent.IO_ERROR,loadUrlHandler); 
	loader.addEventListener(Event.COMPLETE,loadUrlHandler); 
	loader.addEventListener(ProgressEvent.PROGRESS,loadUrlHandler); 
    
    request.contentType = 'application/octet-stream';
    request.method = URLRequestMethod.POST;
    request.data = myByteArray;
    loader.load(request);
}

private function loadUrlHandler(event:Event):void{
	switch(event.type){
		case IOErrorEvent.IO_ERROR:
			logger.debug("load error "+IOErrorEvent(event).text);
			break;
		case Event.COMPLETE:
			logger.debugMore("ok",event);
			break;
		case ProgressEvent.PROGRESS:
			break;
	}
}

//获取配置文件数据
public function result(data:Object):void{
	var list:ArrayCollection = data.result.assets.icon_type;
	var listIconType:Array = new Array();
	for each(var item:Object in list){
		var itVO:IconTypeVO = new IconTypeVO();
		itVO.label = item.label;
		itVO.level = item.level;
		itVO.type = item.type;
		
		for each(var icon:Object in item.icon){
			var iconVO:IconVO = new IconVO();
			iconVO.label = icon.label;
			iconVO.level = icon.level;
			iconVO.url = icon.url;
			iconVO.clazz = icon.clazz;
			iconVO.type = icon.type;
			iconVO.parent = itVO;
			itVO.icon.push(iconVO);
			
		}
		listIconType.push(itVO);
	}
	listCate.dataProvider = listIconType;
	listCate.selectedIndex = 0;
	changeCateHandler(null);
}

private function changeCateHandler(event:ListEvent):void{
	listIcon.dataProvider = listCate.selectedItem.icon;
}

public function fault(info:Object):void{
	vsMain.selectedIndex = 1;
	logger.debugMore("load xml error",info.fault);
}

private var f:FileReference = new FileReference;
private var imageUrl:String;
private function uploadCompleteHandler(event:ResultEvent):void{
	LoadProgressBar.hide();
	if(event.result.indexOf(this.userId)!=-1){
		var toast:Toast = Toast.show("上传图片空间","图片已上传成功！现在要打开看看吗？");
		toast.addEventListener(CloseEvent.CLOSE,viewImageHandler);
		imageUrl = event.result as String;
//		logger.debug("url="+event.result);
//		f.download(new URLRequest(event.result as String));
	}
}

private function viewImageHandler(event:CloseEvent){
	if(event.detail == Toast.YES){
		navigateToURL(new URLRequest(imageUrl),"_blank");
	}
}

private function errorHandler(event:FaultEvent):void{
	logger.debug("upload error "+event.message);
	LoadProgressBar.hide();
}

private function dragCateListHandler(event:MouseEvent):void{
	switch(event.type){
		case MouseEvent.MOUSE_DOWN:
			library.startDrag();
			break;
		case MouseEvent.MOUSE_UP:
			library.clearStyle("right");		
			library.stopDrag();
			break;
	}
}



//添加图形到画布上
var cs:CustomShape;
private function addShapeHandler(event:Event):void{
	var item:IconVO = listIcon.selectedItem as IconVO;//event.request.item;
	var shape:Canvas ;
	if(item.clazz){
		var ShapeClass:Class = getDefinitionByName(item.clazz) as Class;
		shape = new ShapeClass(item.type);
	}else{
		shape = new SimpleImage();
	}
	shape.data = item;
	shape.addEventListener(MouseEvent.MOUSE_DOWN,mouseHandler);
	shape.addEventListener(MouseEvent.MOUSE_UP,mouseHandler);	
	shape.label = item.label;
	shape.toolTip = item.label+"["+item.parent.type+"]";
//	shape.name = item.parent.type+"-"+Math.random();
	//如果是直接双击列表添加的，则添加到左上角
	if(event.currentTarget == listIcon){
		shape.x = 0;
		shape.y = 0;
	}else{
		shape.x = canvas.getCanvas().mouseX;
		shape.y = canvas.getCanvas().mouseY;
	}
	canvas.addShape(shape);
}

private function mouseHandler(event:MouseEvent):void{
	switch(event.type){
		case MouseEvent.MOUSE_DOWN:
			var bounds:Rectangle = new Rectangle(0,0,canvas.getCanvas().width-event.currentTarget.width,
				canvas.getCanvas().height-event.currentTarget.height);
			event.currentTarget.startDrag();
			break;
		case MouseEvent.MOUSE_UP:
			event.currentTarget.stopDrag();
			break;
	}
}

//由于安全策略问题，不方便直接通过Flex获取淘宝图片，因此使用了PHP来获取图片数据
public function addImageHandler(url:String):void{
	downloadService.url = DOWNLOAD_IMAGE;
	var r:Object = new Object();
	r.url = url;
	downloadService.send(r);
}

//添加文本对象
public function addTextHandler(text:String,fontName:String,fontSize:int,color:uint):void{
	var t:Text = new Text();
	t.text = text;
	t.setStyle("fontFamily",fontName);
	t.setStyle("fontSize",fontSize);
	t.setStyle("color",color);
	canvas.addText(t);
}

//下载图片完成
private function downloadCompleteHandler(event:ResultEvent):void{
	var decoder:Base64Decoder = new Base64Decoder();
	decoder.decode(event.result.toString());
	var image:Image = new Image();
	image.maintainAspectRatio = false;
	image.addEventListener(Event.COMPLETE,loadItemImageComplete);
	image.addEventListener(FlexEvent.UPDATE_COMPLETE,loadItemImageComplete);
	image.source = decoder.toByteArray();
//	image.width = 100;
//	image.height = 80;
	
	canvas.addShape(image);
	
	vsMain.selectedIndex = 0;
	LoadProgressBar.hide();	
}

private function downloadLocalCompleteHandler(event:ResultEvent):void{
	Toast.showMsg("下载完成");
}

private function loadItemImageComplete(event:Event):void{
	switch(event.type){
		case FlexEvent.UPDATE_COMPLETE:
			break; 
	}
}

private function changeWidthHandler(event:ItemClickEvent):void{
	canvas.shapeWidth = event.item.data as Number;
}

//获取宝贝图片
private function browserHandler(event:ItemClickEvent):void{

}

private function getTypes():Array {
    var allTypes:Array = new Array(getImageTypeFilter());
    return allTypes;
}

private function getImageTypeFilter():FileFilter {
    return new FileFilter("本地图片(*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
}

private function uploadHandler(event:Event):void {
	switch(event.type){
		case Event.SELECT:
			LoadProgressBar.show();
   			file.upload(uploadURL);
			break;
		case Event.COMPLETE:
			logger.debug("upload complete");
			LoadProgressBar.hide();
			break;
		case IOErrorEvent.IO_ERROR:
			logger.debug("upload error."+IOErrorEvent(event).text);
			break;
		case ProgressEvent.PROGRESS:
			break;
		case DataEvent.UPLOAD_COMPLETE_DATA:
			LoadProgressBar.hide();
			var img:Image = new Image();
			var decoder:Base64Decoder = new Base64Decoder();
			decoder.decode(DataEvent(event).data);
			img.source = decoder.toByteArray();
			img.maintainAspectRatio = false;
			canvas.addShape(img);
			break;
	}
	    
}


private function heightChangeHandler(event:Event):void{
	switch(event.type){
		case FlexEvent.ENTER:
		case NumericStepperEvent.CHANGE:
			canvas.shapeHeight = txtHeight.value ;
			break;
		case MouseEvent.MOUSE_WHEEL:
		case FlexMouseEvent.MOUSE_WHEEL_OUTSIDE:
			var value:int = txtHeight.value;
			if(MouseEvent(event).delta<0){
				value--;
				if(value<100) value = 100;
			}else {
				value++;
				
			}
			
			txtHeight.value = value;
			canvas.shapeHeight = value;
			break;
	}
}
/* 
private var oldColor:uint = 0;
private function colorPreviewHandler(event:Event):void{
	if(oldColor == 0 )	oldColor = cpBg.selectedColor;
	switch(event.type){
		case ColorPickerEvent.ITEM_ROLL_OVER:
			canvas.changeBgColor(ColorPickerEvent(event).color);
			break;
		case ColorPickerEvent.ITEM_ROLL_OUT:
		case MouseEvent.ROLL_OUT:
		case FlexMouseEvent.MOUSE_DOWN_OUTSIDE:
			canvas.changeBgColor(oldColor);
			break;
		case ColorPickerEvent.CHANGE:
			oldColor = cpBg.selectedColor;
			break;
	}
}
 */
private function resultHandler(event:ResultEvent):void{
	logger.debugMore("result",event.result);
}

private function faultHandler(event:FaultEvent):void{
	logger.debug("ERROR："+event.message);
}

//鼠标经过时图片预览
private function itemRollHandler(event:ListEvent):void{
	var p:Point = event.itemRenderer.localToGlobal(new Point());
	switch(event.type){
		case ListEvent.ITEM_ROLL_OVER:
//			Previewer.show(event.itemRenderer.data.url,
//				p.x,p.y+event.itemRenderer.height);
			break;
		case ListEvent.ITEM_ROLL_OUT:
		case ListEvent.ITEM_CLICK:
//			Previewer.hide();
			break;
	}
}

//字体属性修改
private function changeFontHandler(event:RequestEvent):void{
	var selectedObject:Object = this.getSelectedObject();
	
	//如果当前选择的是文本对象
	if(selectedObject is Text){
		switch(event.type){
			case FontProperties.CHANGE_FONT_TEXT:
				canvas.clearSelection();
				Text(selectedObject).text = event.request as String;
				canvas.addSelection(selectedObject);
				break;
			case FontProperties.CHANGE_FONT_NAME:
				Text(selectedObject).setStyle("fontFamily",event.request);
				break;
			case FontProperties.CHANGE_FONT_SIZE:
				Text(selectedObject).setStyle("fontSize",event.request);
				break;
			case FontProperties.CHANGE_FONT_COLOR:
				Text(selectedObject).setStyle("color",event.request);
				break;
		}
	}
}

private function changeShapePropHandler(event:RequestEvent):void{
	var selectedObject:Object;
	var selection:Array = canvas.getSelection();
	if(selection!=null && selection.length>0){
		selectedObject = selection[0];
	}
	
	var value:String = event.request as String;
	//如果当前选择的是文本对象
	if(selectedObject is CustomShape){
		switch(event.type){
			case CustomShapeProperties.CHANGE_BORDER_THICKNESS:
				CustomShape(selectedObject).lineThickness = int(value);
				break;
			case CustomShapeProperties.CHANGE_BORDER_COLOR:
				CustomShape(selectedObject).lineColor = uint(value);
				break;
			case CustomShapeProperties.CHANGE_FILL_TYPE:
			case CustomShapeProperties.CHANGE_COLOR:
				CustomShape(selectedObject).fillType = customShapeProperties.cboFillType.value.toString();
				switch(customShapeProperties.cboFillType.value){
					case CustomShape.FILL_SOLID:
						CustomShape(selectedObject).color1 = customShapeProperties.cpColor1.selectedColor;
						break;
					case CustomShape.FILL_GRADIENT:
						var cs:Array = value.split(",");
						CustomShape(selectedObject).color1 = customShapeProperties.cpColor1.selectedColor;
						CustomShape(selectedObject).color2 = customShapeProperties.cpColor2.selectedColor;
						break;
				}
				break;
			case CustomShapeProperties.CHANGE_ANGLE:
				CustomShape(selectedObject).angle = int(value)*Math.PI/180;
				break;
			case CustomShapeProperties.CHANGE_ALPHA:
				CustomShape(selectedObject).alpha = Number(value);
				break;
		}
	}
}

private function changeSimpleImagePropHandler(event:RequestEvent):void{
	var selectedObject:Object;
	var selection:Array = canvas.getSelection();
	if(selection!=null && selection.length>0){
		selectedObject = selection[0];
	}
	
	//如果当前选择的是文本对象
	if(selectedObject is DisplayObject){
		switch(event.type){
			case SimpleImageProperties.CHANGE_ALPHA:
				DisplayObject(selectedObject).alpha = Number(event.request);
				break;
		}
	}
}

private function showBackgroundMaker(event:MouseEvent):void{
	var p:Point = event.target.localToGlobal(new Point());
	var maker:BackgroundMaker = BackgroundMaker.show(null,10,p.y+event.target.height);
	maker.addEventListener(SolidSchemeRenderer.SELECT_SOLID_COLOR,selectHandler);
	maker.addEventListener(GradientSchemeRenderer.SELECT_GRADIENT_COLOR,selectHandler);
	maker.addEventListener(PatternRenderer.SELECT_IMAGE,selectHandler);
}

private function selectHandler(event:RequestEvent):void{
	switch(event.type){
		case SolidSchemeRenderer.SELECT_SOLID_COLOR:
			var color:String = event.request as String;
			canvas.changeBgColor(uint(color));
			break;
		case GradientSchemeRenderer.SELECT_GRADIENT_COLOR:
			var colors:Array = (event.request.color as ArrayCollection).toArray();
			var ratios:Array = event.request.ratios;
			var type:String = event.request.type;
			var maker:BackgroundMaker = event.currentTarget as BackgroundMaker;
			canvas.drawGradientBg(colors,ratios,type,maker.rbgDirection.selectedValue=="h"?0:90);
			break;
		case PatternRenderer.SELECT_IMAGE:
			canvas.drawImageBg(event.request as Image);
			break;
	}
	event.currentTarget.hide();
}

private function changeCanvasBgColor(event:MouseEvent):void{
	switch(event.target){
		case bgTrans:
			canvas.changeCanvasColor(0);
			break;
		case bgGray:
			canvas.changeCanvasColor(1);
			break;
		case bgDark:
			canvas.changeCanvasColor(2);
			break;
	}
	
}



private function picSourceHandler(event:MenuEvent):void{
	switch(event.index){
		case 0://来自模板
			vsMain.selectedIndex = 1;
			if(listTemplates.dataProvider == null){
				loadTemplates();
			}

			break;
		case 1://获取出售中的宝贝
			vsMain.selectedIndex = 2;
			getItems(pageNo,pageSize);
			break;
		case 2://本地上传
			file.browse(getTypes());
			break;
	}
}

private var templatesResponder:TemplatesResponder;
private function loadTemplates():void{
	if(templatesResponder==null){
		templatesResponder = new TemplatesResponder(hlTemplateType,listTemplates);
	}
	var loaderTemplates:LoadXMLDelegate;
	loaderTemplates = new LoadXMLDelegate(templatesResponder,TEMPLATES_URL,"object");
	loaderTemplates.load();
}


//获取商品列表
private function getItems(pageNo:int ,pageSize:int):void{
	var params:Array = new Array();
	taoBaoUtils.pushParam(params,"page_no",pageNo);
	taoBaoUtils.pushParam(params,"page_size",pageSize);
	taoBaoUtils.pushParam(params,"nicks",nick);
	taoBaoUtils.invoke("num_iid,title,nick,pic_url",ProductImageMaster.METHOD_ITEMS_GET,params,app.top_session);
}


//获取商品的翻页处理
public var pageNo:int = 1;
public var totalPage:int;
public var pageSize:int = 10;
private function pageHandler(event:ItemClickEvent):void{
	switch(event.index){
		case 0://首页
			pageNo = 1;
			break;
		case 1://上页
			pageNo--;
			if(pageNo <1){
				pageNo = 1;
			}
			break;
		case 2://下页
			pageNo++;
			if(pageNo>totalPage){
				pageNo = totalPage;
			}
			break;
		case 3://尾页
			pageNo = totalPage;
			break;
	}
	
	getItems(pageNo,pageSize);
}

private function getCategory():void{
	var params:Array = new Array();
	taoBaoUtils.invoke("picture_category_id,picture_category_name,total",ProductImageMaster.METHOD_GET_CATEGORY,params,app.top_session);
}
//获取我的图片空间图片列表
private function getSpaceItems(cate:String,pageNo:int ,pageSize:int):void{
	var params:Array = new Array();
	if(cate){
		taoBaoUtils.pushParam(params,"picture_category_id",cate);
	}
	taoBaoUtils.pushParam(params,"page_no",pageNo);
	taoBaoUtils.pushParam(params,"page_size",pageSize);
	taoBaoUtils.pushParam(params,"nicks",nick);
	taoBaoUtils.invoke("picture_id,picture_category_id,picture_path,pixel",ProductImageMaster.METHOD_GET_PICTURE,params,app.top_session);
}

public var spacePageNo:int = 1;
public var spaceTotalPage:int;
public var spacePageSize:int = 10;
private function spacePageHandler(event:ItemClickEvent):void{
	switch(event.index){
		case 0://首页
			spacePageNo = 1;
			break;
		case 1://上页
			spacePageNo--;
			if(spacePageNo <1){
				spacePageNo = 1;
			}
			break;
		case 2://下页
			spacePageNo++;
			if(spacePageNo>spaceTotalPage){
				spacePageNo = spaceTotalPage;
			}
			break;
		case 3://尾页
			spacePageNo = spaceTotalPage;
			break;
	}
	getSpaceItems(null,spacePageNo,spacePageSize);
}


private function getColorHandler():void{
	if(canvas.gettingColor){
		canvas.gettingColor = false;
//		btnGetColor.label = "取色";
	}else{
		canvas.dispatchEvent(new Event(DesignCanvas.START_GET_COLOR));
//		btnGetColor.label = "取色中...";
	}
}

private function getColorCompleteHandler(event:RequestEvent):void{
	var c:uint = event.request as uint;
//	txtColor.text = "#"+ColorUtils.toHex(c);
	if(event.type == DesignCanvas.END_GET_COLOR){
//		btnGetColor.label = "取色";
	}
}

private function layerHandler(event:RequestEvent):void{
		var tmpList:Object = layers.dataProvider;
		var list:Array;
		if(tmpList){
			list = (tmpList as ArrayCollection).toArray();
		}
		if(list==null){
			list = new Array();
		}
		switch(event.type){
			case DesignCanvas.ADD_LAYER_CHILD:
				list.unshift(event.request);
				break;
			case DesignCanvas.REMOVE_LAYER_CHILD:
				var idx:int = 0;
				for each(var item:Object in list){
					if(item.name == event.request.selectedItem.name){
						list.splice(idx,1);
					}
					idx++;
				}
				break;
		}
		
		layers.dataProvider = list;
}

private function changeVisibleHandler(event:RequestEvent):void{
	for each(var item:Object in canvas.canvas.getChildren()){
		if(item.name == event.request.data.name){
			item.visible = event.request.visible;
			if(canvas.currentlySelected && canvas.currentlySelected.length>0){
				canvas.clearSelection();
			}
			break;
		}
	}
}

private function selectLayerHandler(event:ListEvent):void{
	for each(var item:Object in canvas.canvas.getChildren()){
		if(item.name == layers.selectedItem.selectedItem.name){
			canvas.clearSelection();
			canvas.addSelection(item);
			break;
		}
	}
}

private function selectItemHandler(event:ListEvent):void{
	LoadProgressBar.show();
	addImageHandler(listItems.selectedItem.pic_url);
}

private function selectSpaceItemHandler(event:ListEvent):void{
	LoadProgressBar.show();
	addImageHandler(listSpaceItems.selectedItem.pic_url);
}

private function changeType(event:ListEvent):void{
	listTemplates.dataProvider = templatesResponder.listTemplate[hlTemplateType.selectedIndex];
}

private function changeCate(event:ListEvent):void{
	var cate:String = hlCate.selectedItem.data;
	if(cate=="") cate == null;
	getSpaceItems(cate,spacePageNo,spacePageSize);
}

private function selectTemplateHandler(event:ListEvent):void{
	var image:Image = new Image();
	image.source = listTemplates.selectedItem.url;
	image.maintainAspectRatio = false;
	canvas.addShape(image);
	vsMain.selectedIndex = 0;
}

private var myMenu:Menu;
private function showImageMenu():void {
    myMenu= Menu.createMenu(btnImportImage, imageMenu, false);
    myMenu.labelField="@label"
    myMenu.addEventListener("itemClick", importImageHandler);
    
    var p:Point =btnImportImage.localToGlobal(new Point());

    myMenu.show(p.x , p.y + 21);
}

private function importImageHandler(event:MenuEvent):void{
	switch(event.index){
		case 0://来自模板
			vsMain.selectedIndex = 1;
			if(listTemplates.dataProvider == null){
				loadTemplates();
			}

			break;
		case 1://获取出售中的宝贝
			vsMain.selectedIndex = 2;
			getItems(pageNo,pageSize);
			break;
		
		case 2://我的图片空间
			vsMain.selectedIndex = 3;
			getCategory();//获取图片分类
			getSpaceItems(null,spacePageNo,spacePageSize);
			break;
		case 3://本地上传
			file.browse(getTypes());
			break;
	}
}

private function gotoBangPai():void{
	navigateToURL(new URLRequest(BANGPAI),"_blank");
}
private function gotoTutorials():void{
	navigateToURL(new URLRequest(TUTORIALS),"_blank");
}

private function exitHandler():void{
	navigateToURL(new URLRequest(EXIT_URL),"_top");
	
}


//反馈处理
private function feedbackHandler():void{
	var advice:Advice = Advice.show();
	advice.addEventListener(Advice.FEEDBACK,commitFeedback);
	

}

private function commitFeedback(event:RequestEvent):void
{
	var params:Object = new Object();
	params.nick = this.nick;
	params.msg = event.request as String;
	feedbackService.send(params);
}

private function feedbackSuccessHandler(event:ResultEvent):void{
	Toast.showMsg("谢谢您的反馈，我们会及时处理的~");
}

//设计画布上改变对象层级时，刷新图层列表的数据顺序
private function changeIndexHandler(event:RequestEvent):void{
	var ary:ArrayCollection = ArrayCollection(layers.dataProvider);
	for each(var item:UIComponent in canvas.getCanvas().getChildren()){
		for (var i:int =0;i<ary.length;i++){
			if(item.name == ary.getItemAt(i).selectedItem.name){
				ary.getItemAt(i).childIndex = canvas.getCanvas().getChildIndex(item);
				break;
			}
		}
		
	}
	
	var sort:Sort = new Sort();
	sort.fields = [new SortField("childIndex",false,true)];
	ary.sort = sort;
	ary.refresh();

}

//从图层列表中删除数据
private function deleteItemHandler(event:RequestEvent):void{
	var ary:ArrayCollection = layers.dataProvider as ArrayCollection;
	
	for(var i:int = 0;i<ary.length;i++){
		if(ary.getItemAt(i).selectedItem == event.request){
			logger.debug(i);
			ary.removeItemAt(i);
			break;
		}
	}
}

//取当前选中的对象，只取一个
private function getSelectedObject():Object{
	var selectedObject:Object;
	var selection:Array = canvas.getSelection();
	if(selection!=null && selection.length>0){
		selectedObject = selection[0];
	}
	return selectedObject;
}

private function changePosition(event:Event):void{
	var selectedObject:Object = getSelectedObject();
	if(!selectedObject) return;
	
	switch(event.target){
		case txtX:
			selectedObject.x = int(txtX.text);
			break;
		case txtY:
			selectedObject.y = int(txtY.text);
			break;
	}
	canvas.clearSelection();
	canvas.addSelection(selectedObject);
}

//发光效果
private function changeGlow():void{
	var selectedObject:Object = getSelectedObject();
	
	if(!selectedObject) return;
	
	if(chkGlow.selected){
		EffectUtils.setFlowEffect(selectedObject,cpGlowColor.selectedColor,Number(txtGlowSize.text));
	}else{
		selectedObject.filters = null;
	}
}


override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
	super.updateDisplayList(unscaledWidth,unscaledHeight);
//	GraphicsUtils.drawBackground(imgHead,title);
		
} 

